package com.example.pclimb.ui.guide;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityApplyGuideBinding;
import com.example.pclimb.model.GuideImage;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.adapters.CertificateImageAdapter;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.GuideImageViewModel;
import com.example.pclimb.viewmodel.UserViewModel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 申请成为陪爬向导的活动
 */
public class ApplyGuideActivity extends AppCompatActivity {

    private static final String TAG = "ApplyGuideActivity";
    private static final int MAX_IMAGES = 3;
    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;
    
    private ActivityApplyGuideBinding binding;
    private UserViewModel userViewModel;
    private GuideImageViewModel guideImageViewModel;
    private User currentUser;
    private CertificateImageAdapter imageAdapter;
    
    private Uri currentPhotoUri;
    private File photoFile;
    
    // 拍照结果处理
    private ActivityResultLauncher<Uri> takePictureLauncher = registerForActivityResult(
            new ActivityResultContracts.TakePicture(),
            result -> {
                if (result && photoFile != null) {
                    // 拍照成功，保存图片记录
                    saveImageToDatabase(photoFile.getAbsolutePath());
                }
            });
    
    // 从相册选择图片结果处理
    private ActivityResultLauncher<String> pickImageLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            uri -> {
                if (uri != null) {
                    try {
                        // 将选择的图片保存到应用私有目录
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                        File imageFile = createImageFile();
                        FileOutputStream fos = new FileOutputStream(imageFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                        fos.close();
                        
                        // 保存图片记录
                        saveImageToDatabase(imageFile.getAbsolutePath());
                    } catch (IOException e) {
                        Log.e(TAG, "保存选择的图片出错: ", e);
                        Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityApplyGuideBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 初始化ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        guideImageViewModel = new ViewModelProvider(this).get(GuideImageViewModel.class);

        // 初始化图片适配器
        setupImageRecyclerView();

        // 获取当前用户信息
        int userId = SharedPreferencesUtil.getUserId(this);
        if (userId != -1) {
            Log.d(TAG, "加载用户信息，用户ID: " + userId);
            userViewModel.getUserById(userId).observe(this, user -> {
                if (user != null) {
                    Log.d(TAG, "成功加载用户信息: " + user.getUsername());
                    currentUser = user;
                    
                    // 加载用户已上传的证书图片
                    guideImageViewModel.getUserImages(userId).observe(this, images -> {
                        if (images != null && !images.isEmpty()) {
                            binding.recyclerCertificateImages.setVisibility(View.VISIBLE);
                            imageAdapter.setImages(images);
                        }
                    });
                    
                    // 检查用户是否已经是向导或已申请
                    if (user.isGuide() || user.getUserType() == User.TYPE_GUIDE || user.isGuideApproved()) {
                        // 用户已经是向导
                        binding.layoutForm.setVisibility(View.GONE);
                        binding.layoutAlreadyGuide.setVisibility(View.VISIBLE);
                        binding.btnSubmit.setVisibility(View.GONE);
                    } else if (user.isGuideApplied() || user.getGuideApplication() > User.APPLICATION_NONE) {
                        // 用户已申请但未审批
                        binding.layoutForm.setVisibility(View.GONE);
                        binding.layoutAlreadyGuide.setVisibility(View.GONE);
                        
                        // 显示正在审核的提示
                        View pendingView = getLayoutInflater().inflate(R.layout.layout_application_pending, null);
                        binding.btnSubmit.setVisibility(View.GONE);
                        
                        if (binding.getRoot() instanceof ViewGroup) {
                            ((ViewGroup) binding.getRoot()).addView(pendingView);
                        }
                    } else {
                        // 普通用户，可以申请
                        binding.layoutForm.setVisibility(View.VISIBLE);
                        binding.layoutAlreadyGuide.setVisibility(View.GONE);
                        binding.btnSubmit.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置提交按钮点击事件
        binding.btnSubmit.setOnClickListener(v -> submitApplication());
        
        // 设置添加图片按钮点击事件
        binding.btnAddImage.setOnClickListener(v -> showImagePickerDialog());
    }
    
    /**
     * 设置证书图片RecyclerView
     */
    private void setupImageRecyclerView() {
        imageAdapter = new CertificateImageAdapter(this);
        binding.recyclerCertificateImages.setLayoutManager(new GridLayoutManager(this, 3));
        binding.recyclerCertificateImages.setAdapter(imageAdapter);
        
        // 设置图片点击和删除事件
        imageAdapter.setOnImageClickListener(new CertificateImageAdapter.OnImageClickListener() {
            @Override
            public void onImageClick(GuideImage image, int position) {
                // 查看大图
                showLargeImage(image);
            }

            @Override
            public void onDeleteClick(GuideImage image, int position) {
                // 删除图片
                guideImageViewModel.deleteImage(image);
                imageAdapter.removeImage(position);
                
                // 如果没有图片了，隐藏RecyclerView
                if (imageAdapter.getItemCount() == 0) {
                    binding.recyclerCertificateImages.setVisibility(View.GONE);
                }
            }
        });
    }
    
    /**
     * 显示大图查看
     */
    private void showLargeImage(GuideImage image) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_image_preview, null);
        ImageView imageView = view.findViewById(R.id.img_preview);
        
        // 加载图片
        if (image.getImagePath() != null && !image.getImagePath().isEmpty()) {
            Glide.with(this)
                    .load(new File(image.getImagePath()))
                    .into(imageView);
        } else if (image.getImageUrl() != null && !image.getImageUrl().isEmpty()) {
            Glide.with(this)
                    .load(image.getImageUrl())
                    .into(imageView);
        }
        
        builder.setView(view);
        builder.setTitle(R.string.image_preview);
        builder.setPositiveButton(R.string.cancel, null);
        builder.show();
    }
    
    /**
     * 显示图片选择对话框
     */
    private void showImagePickerDialog() {
        // 检查是否已达到最大图片数
        if (imageAdapter.getItemCount() >= MAX_IMAGES) {
            Toast.makeText(this, R.string.max_images_reached, Toast.LENGTH_SHORT).show();
            return;
        }
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_image_source);
        String[] options = {getString(R.string.camera), getString(R.string.gallery)};
        
        builder.setItems(options, (dialog, which) -> {
            if (which == 0) {
                // 拍照
                if (checkCameraPermission()) {
                    takePicture();
                }
            } else {
                // 从相册选择
                if (checkStoragePermission()) {
                    pickImage();
                }
            }
        });
        
        builder.show();
    }
    
    /**
     * 检查相机权限
     */
    private boolean checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
            return false;
        }
        return true;
    }
    
    /**
     * 检查存储权限
     */
    private boolean checkStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
            return false;
        }
        return true;
    }
    
    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePicture();
            } else {
                showPermissionDeniedDialog(R.string.permission_camera);
            }
        } else if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            } else {
                showPermissionDeniedDialog(R.string.permission_storage);
            }
        }
    }
    
    /**
     * 显示权限被拒绝的对话框
     */
    private void showPermissionDeniedDialog(int messageResId) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.permission_required)
                .setMessage(messageResId)
                .setPositiveButton(R.string.permission_settings, (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
    
    /**
     * 拍照
     */
    private void takePicture() {
        try {
            photoFile = createImageFile();
            currentPhotoUri = FileProvider.getUriForFile(this,
                    getApplicationContext().getPackageName() + ".fileprovider",
                    photoFile);
            takePictureLauncher.launch(currentPhotoUri);
        } catch (IOException e) {
            Log.e(TAG, "创建图片文件失败: ", e);
            Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 从相册选择图片
     */
    private void pickImage() {
        pickImageLauncher.launch("image/*");
    }
    
    /**
     * 创建图片文件
     */
    private File createImageFile() throws IOException {
        // 创建图片文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        
        // 创建图片文件
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }
    
    /**
     * 保存图片到数据库
     */
    private void saveImageToDatabase(String imagePath) {
        if (currentUser != null) {
            GuideImage guideImage = new GuideImage(currentUser.getId(), imagePath);
            guideImageViewModel.addImage(guideImage);
            
            // 显示RecyclerView并添加图片到适配器
            binding.recyclerCertificateImages.setVisibility(View.VISIBLE);
            
            // 手动创建并添加图片预览到UI
            addImagePreview(imagePath);
        }
    }
    
    /**
     * 添加图片预览到UI
     */
    private void addImagePreview(String imagePath) {
        ImageView imageView = new ImageView(this);
        int sizePx = (int) (getResources().getDisplayMetrics().density * 80);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(sizePx, sizePx);
        params.setMargins(8, 0, 8, 0);
        imageView.setLayoutParams(params);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        
        // 加载图片
        Glide.with(this)
                .load(new File(imagePath))
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .centerCrop()
                .into(imageView);
        
        // 添加到预览布局
        binding.layoutImagePreview.addView(imageView);
    }

    /**
     * 提交陪爬向导申请
     */
    private void submitApplication() {
        // 获取表单数据
        String experience = binding.etExperience.getText().toString().trim();
        String certification = binding.etCertification.getText().toString().trim();
        
        // 验证表单
        if (TextUtils.isEmpty(experience)) {
            binding.tilExperience.setError("请输入您的登山经验");
            return;
        }
        
        if (TextUtils.isEmpty(certification)) {
            binding.tilCertification.setError("请输入您的证书信息");
            return;
        }
        
        // 检查是否上传了证书图片
        if (imageAdapter.getItemCount() == 0) {
            Toast.makeText(this, "请上传至少一张证书图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示进度条
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.btnSubmit.setEnabled(false);
        
        try {
            // 更新用户信息，将申请状态设置为待审核
            if (currentUser != null) {
                Log.d(TAG, "提交向导申请: " + currentUser.getUsername());
                
                // 保存申请信息 - 同时设置新旧字段确保兼容性
                currentUser.setExperience(experience);
                currentUser.setCertification(certification);
                currentUser.setGuideApplication(User.APPLICATION_PENDING);
                currentUser.setGuideApplied(true); // 设置旧字段
                
                // 更新用户信息
                userViewModel.updateUser(currentUser);
                
                // 显示成功提示
                Toast.makeText(this, R.string.application_submitted, Toast.LENGTH_SHORT).show();
                
                // 关闭当前页面
                finish();
            } else {
                binding.progressBar.setVisibility(View.GONE);
                binding.btnSubmit.setEnabled(true);
                Toast.makeText(this, "提交申请失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "提交向导申请出错: ", e);
            binding.progressBar.setVisibility(View.GONE);
            binding.btnSubmit.setEnabled(true);
            Toast.makeText(this, "提交申请失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
} 